<script setup lang="tsx">
import { getListApi as getOrderApi } from '@/api/order'
import { getListApi as getWholesalOrderApi } from '@/api/wholesalOrder'

import { CurdData as orderCurdData } from '@/api/order/types'
import { CurdData } from '@/api/customer/types'
import { useI18n } from '@/hooks/web/useI18n'
const { push } = useRouter()

const { t } = useI18n()
// import FollowUpRecords from './FollowUpRecords.vue'
// import OperationLog from './OperationLog.vue'
// 使用 ref 声明响应式变量 isExpanded
const isExpanded = ref(true)

// 切换展开/收起状态的方法
const togglePanel = () => {
  isExpanded.value = !isExpanded.value
}
const activeName = ref('order')

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<CurdData>>,
    default: () => null
  }
})

const handleTabClick = (tab: any) => {
  console.log(activeName)
  fetchData(tab.paneName)
}

const timeLineData = ref<orderCurdData[]>([])
const dateddd = ref('')
const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

const dateChange = (val: [Date, Date]) => {
  if (val) {
    const [startDate, endDate] = val

    // 设置开始时间的时分秒为 00:00:00
    startDate.setHours(0, 0, 0, 0)

    // 设置结束时间的时分秒为 23:59:59
    endDate.setHours(23, 59, 59, 999)

    // 格式化开始时间为 yyyy-MM-dd HH:mm:ss
    const formattedStartDate = startDate
      .toLocaleString('en-GB', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      })
      .replace(',', '')
      .replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$2-$1') // 转换日期格式为 yyyy-MM-dd
      .replace(/(\d{2}):(\d{2}):(\d{2})/, '$1:$2:$3') // 格式化时分秒

    // 格式化结束时间为 yyyy-MM-dd HH:mm:ss
    const formattedEndDate = endDate
      .toLocaleString('en-GB', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      })
      .replace(',', '')
      .replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$2-$1') // 转换日期格式为 yyyy-MM-dd
      .replace(/(\d{2}):(\d{2}):(\d{2})/, '$1:$2:$3') // 格式化时分秒

    console.log('开始时间:', formattedStartDate)
    console.log('结束时间:', formattedEndDate)
    fetchData(activeName.value, [formattedStartDate, formattedEndDate])
  }
}

const fetchData = async (type: string, date?: [string, string]) => {
  interface FetchParams {
    user_id?: number
    start_time?: string
    end_time?: string
  }

  const params: FetchParams = {
    user_id: props.currentRow?.id
  }

  if (date && Array.isArray(date) && date.length === 2) {
    params.start_time = date[0]
    params.end_time = date[1]
  }

  if (type === 'order') {
    let order_category = 'order'
    const resp = await getOrderApi({ ...params, order_category })
    timeLineData.value = resp.data.list
  } else {
    const resp = await getWholesalOrderApi(params)
    timeLineData.value = resp.data.list
  }
}

fetchData(activeName.value)

//跳转
const handleJump = (type: string, row: Record<string, any>) => {
  if ('order' === type) {
    push({
      path: `/order/order-management/detail`,
      query: { id: row.id }
    })
  } else {
    push({
      path: `/order/wholesal-order-management/detail`,
      query: { id: row.id }
    })
  }
}
</script>

<template>
  <el-card shadow="always">
    <div @click="togglePanel" class="header cursor-pointer">
      <span>合同订单</span>
      <el-icon v-if="isExpanded">
        <el-icon-arrow-down />
      </el-icon>
      <el-icon v-else>
        <el-icon-arrow-right />
      </el-icon>
    </div>
    <el-collapse-transition>
      <div v-show="isExpanded" class="w-full">
        <div class="block m-b-5">
          <el-date-picker
            v-model="dateddd"
            type="daterange"
            unlink-panels
            range-separator="To"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            @change="dateChange"
          />
        </div>

        <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleTabClick">
          <el-tab-pane label="普通订单" name="order">
            <el-card shadow="always" class="card-container"
              ><el-timeline>
                <el-timeline-item
                  v-for="item in timeLineData"
                  :key="item.id"
                  :timestamp="item.create_time ? item.create_time.toLocaleString() : ''"
                  placement="top"
                >
                  <el-card>
                    <ElLink @click="handleJump('order', item)" type="primary">
                      {{ item.order_no }}
                    </ElLink>
                    <p>{{ t('order.theAmountOfTheOrder') }}: {{ item.total_amount }}</p>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </el-card>
          </el-tab-pane>
          <el-tab-pane label="经销商订单" name="wholesal">
            <el-card shadow="always" class="card-container">
              <el-timeline>
                <el-timeline-item
                  v-for="item in timeLineData"
                  :key="item.id"
                  :timestamp="item.create_time ? item.create_time.toLocaleString() : ''"
                  placement="top"
                >
                  <el-card>
                    <ElLink @click="handleJump('wholesal', item)" type="primary">
                      {{ item.order_no }}
                    </ElLink>
                    <p>{{ t('order.theAmountOfTheOrder') }}: {{ item.total_amount }}</p>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-collapse-transition>
  </el-card>
</template>

<style scoped>
.header {
  display: flex;
  height: 40px;
  padding: 0 10px;
  margin-bottom: 10px;
  font-weight: 900;
  cursor: pointer;
  background-color: #f3f3f3;
  border-radius: 5px;
  align-items: center;
  justify-content: space-between;
}
</style>
